package com.dolawing.phonecallapp.utils;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AudioUtil {
    private static MediaRecorder recorder;//录音类
    private static MediaPlayer player;//播放类
    //获取sd根目录
    //public static final String ROOT_FILE = Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"MyAudio";

    //开始录音
    public static void startRecordAudio(Context context , String AudioSaveName){
        File ROOT_FILE = context.getExternalFilesDir("MyAudio");
        if(recorder ==null){
            recorder =new MediaRecorder();
        }
        /**
         1.音频输出格式(setOuputFormat)设置为 MediaRecorder.OutputFormat.MPEG_4
         2.编码格式(setAudioEncoder)设置为 MediaRecorder.AudioEncoder.AAC
         3.保存文件名后缀名设置为“*.mp3”
         **/
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置录音来源 :麦克风
        recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//设置输出格式
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);//设置编码格式
        String path =ROOT_FILE.getPath() + File.separator + AudioSaveName;
        recorder.setOutputFile(path);//设置输出路径
        try {
            recorder.prepare();//准备
            recorder.start();//开始录音
            Toast.makeText(context,"开始录音", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void stopRecordAudio(Context context){
        if(recorder !=null){
            recorder.stop();//停止录音
            recorder.reset();//重置
            recorder.release();//释放资源
            recorder =null;
            Toast.makeText(context,"停止录音",Toast.LENGTH_SHORT).show();
        }
    }

    //开始播放
    public static void startPlayerAudio(Context context , String AudioName){
        File ROOT_FILE = context.getExternalFilesDir("MyAudio");
        if(player ==null){
            player =new MediaPlayer();
        }
        try {
            String path = ROOT_FILE.getPath() + File.separator + AudioName;
            Log.i("recordAudio path",path);
            File f = new File(path);
            if (f.isFile()){
                Log.i("file sizes" , String.valueOf(f.length()) );
            }
            File tempFile = new File(path);
            FileInputStream fis = new FileInputStream(tempFile);
            player.reset();
            player.setDataSource(fis.getFD());
            player.prepare();
            player.start();
        } catch (Exception e) {
            Log.i("player error",e.toString());
        }
    }

    //开始播放
    public static void stopPlayerAudio(){
        try {
            if (player!=null){
                player.stop();
                player.release();
            }
        } catch (IllegalStateException e) {
            Log.i("player error",e.toString());
        }
    }

    //文件上传
    public static void audioFileUpload(Context context , String url, String AudioName, HashMap<String,Object> paramsMap) {//文件路径
        File ROOT_FILE = context.getExternalFilesDir("MyAudio");
        String path = ROOT_FILE.getPath() + File.separator + AudioName;
        Log.i("录音文件路径：", path);
        File file = new File(path);
        if (file == null || !file.exists()) {
            Log.e("AudioUtil audioUpload", "录音文件不存在");
            return;
        }
        paramsMap.put("uploadfile",file);
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .build();
        MediaType type = MediaType.parse("application/octet-stream");//"text/xml;charset=utf-8"
        MultipartBody.Builder builder=  new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (String key:paramsMap.keySet()){
            Object object = paramsMap.get(key);
            if (!(object instanceof File)){
                builder.addFormDataPart(key,object.toString());
            }else{
                builder.addFormDataPart(key,((File) object).getName(), RequestBody.create(type, (File) object));
            }
        }
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("id", "testid")
                .addHeader("Token","xxxxxxxyyyyyyyyzzzzzzzz")
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("okHttpClient", "onFailure: " + e.getMessage());

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() == 200) {
                    Log.d("okHttpClient", "上传成功");
//                    cameraFacenet("2");
                } else {
                    Log.d("okHttpClient", "上传失败");
                }

            }
        });

    }
}
